﻿using Basic.FlowCollect;
using Basic.FlowExtendService;
using Basic.FlowModel.App;
using Basic.FlowRemoteModel;
using Basic.FlowRemoteModel.NodeFormData.Model;
using Basic.FormRemoteModel.TableRecord.Model;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.Log;

namespace Basic.FlowApplication.AuditLocalEvent.AuditEvent
{
    internal class AppDataSave : IEventHandler<FlowAuditEvent>
    {
        private readonly IFormInterService _Form;
        private readonly IFlowAppCollect _FlowApp;
        private readonly IFlowAppFormRelationCollect _FormRelation;

        public AppDataSave ( IFormInterService form,
            IFlowAppCollect flowApp,
            IFlowAppFormRelationCollect formRelation )
        {
            this._Form = form;
            this._FlowApp = flowApp;
            this._FormRelation = formRelation;
        }

        public void HandleEvent ( FlowAuditEvent data, string eventName )
        {
            if ( data.Log.AppType == FlowAppType.外部应用 )
            {
                return;
            }
            else if ( data.Log.Status == FlowAuditLogStatus.已结束 && data.Log.AuditStatus == FlowAuditStatus.审核通过 )
            {
                AppDto app = this._FlowApp.Get<AppDto>(data.Log.AppId);
                if ( app.SettleFormId.HasValue == false )
                {
                    return;
                }
                DataRelation[] list = this._FormRelation.Gets(app.Id);
                if ( list.IsNull() )
                {
                    return;
                }
                if ( !this._Form.Save(new TableDataRow
                {
                    LogId = data.Log.Id,
                    LinkPK = data.Log.LinkPk,
                    LinkType = data.Log.LinkType,
                    ToFormId = app.SettleFormId.Value,
                    CompanyId = data.Log.CompanyId,
                    Relation = list.ConvertAll(a => new TableColRelation
                    {
                        ColId = a.ColId,
                        ToColId = a.ToColId,
                        FormId = a.FormId,
                        Keywords = a.Keywords,
                    })
                }) )
                {
                    string str = string.Format("logId:{0},toFormId:{1},linkPk:{2}", data.Log.Id, app.SettleFormId.Value, data.Log.LinkPk);
                    new InfoLog("流程数据保存失败!", str, "Flow")
                    {
                        { "relation",list.ToJson()}
                    }.Save();
                }
            }
        }
    }
}
